# ！/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time     :2019/1/5 21:26
# @Author   :Yosef
# E-mail    :wurz529@foxmail.com
# File      :do_testcase_excel_new.py
# Software  :PyCharm Community Edition

import openpyxl
from common.configer import ReadConfig
from common.mylog import Mylog
from common.project_path import ProjectPath

mylog = Mylog("读取excel文件")


class TestCase:
    def __init__(self):
        self.caseId = None
        self.a = None
        self.b = None
        self.expected = None
        self.actual = None
        self.test_result = None


class DoExcel:
    def __init__(self, filepath, sheet_name):
        self.filepath = filepath
        self.sheet_name = sheet_name
        self.conf = ReadConfig(ProjectPath().conf_path()).get_value("test_case_id", "button")

    def read_data(self):
        wb = openpyxl.load_workbook(self.filepath)
        sh = wb[self.sheet_name]
        testdata = []
        try:
            if self.conf == "all":
                for i in range(2, sh.max_row + 1):
                    item = TestCase()
                    item.caseId = sh.cell(i, 1).value
                    item.a = sh.cell(i, 2).value
                    item.b = sh.cell(i, 3).value
                    item.expected = sh.cell(i, 4).value
                    item.actual = sh.cell(i, 5).value
                    item.test_result = sh.cell(i, 6).value
                    testdata.append(item)
            else:
                conf = eval(self.conf)
                new_conf = []
                for run_case_id in conf:
                    run_case_row = run_case_id + 1
                    new_conf.append(run_case_row)
                for i in new_conf:
                    item = TestCase()
                    item.caseId = sh.cell(i, 1).value
                    item.a = sh.cell(i, 2).value
                    item.b = sh.cell(i, 3).value
                    item.expected = sh.cell(i, 4).value
                    item.actual = sh.cell(i, 5).value
                    item.test_result = sh.cell(i, 6).value
                    testdata.append(item)
        except Exception:
            mylog.error("请检查{}文件中[test_case_id]的button的value是否符合要求！！".format(ProjectPath().conf_path()))
            raise Exception("请检查{}文件中[test_case_id]的button的value是否符合要求！！".format(ProjectPath().conf_path()))
        return testdata

    def write_data(self, row, col, value):
        wb = openpyxl.load_workbook(self.filepath)
        ws = wb[self.sheet_name]

        ws.cell(row, col).value = value
        mylog.info("数据写入成功")
        wb.save(self.filepath)


if __name__ == '__main__':
    excel = DoExcel(ProjectPath().test_data_data(), "add_test_data").read_data()
    print(excel[0].caseId)
